<template>
  <div class="color-picker-box">
    <div class="color-picker-title">调色盘</div>
    <!-- 画布用于显示渐变色 -->
    <div class="color-picker" @mousedown="startDrag" @mousemove="handleDrag" @mouseup="endDrag">
      <canvas ref="canvas" :width="canvasWidth" :height="canvasHeight" @click="handleClick"></canvas>
    </div>
    <!-- 颜色选择器，用于点击选择颜色 -->
    <div class="color-selector-wrap">
      <div class="color-selector-name">{{ state.selectedColor }}</div>
      <div class="color-selector" @click="selectColor">
        <div class="color-selector-indicator"
          :style="{ left: indicatorPosition + 'px', backgroundColor: state.selectedColor }">
        </div>
      </div>
    </div>
    <div class="color-picker-title">纯色预设</div>
    <!-- 颜色预设区域 -->
    <div class="color-presets">
      <!-- 循环渲染颜色预设 -->
      <div v-for="(row, index) in colorPresets" :key="index" class="color-preset-row">
        <div v-for="(color, i) in row" :key="i" class="color-preset" :style="{ backgroundColor: color }"
          @click="selectPresetColor(color)"></div>
      </div>
    </div>
    <div class="result">输出结果</div>
    <!-- 显示选中的颜色和颜色索引 -->
    <div class="show-color-box">
      <div class="showColor" :style="{ background: state.selectedColor }"></div>
      <p>{{ state.selectedColor }}</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, reactive, computed } from 'vue';

export default {
  name: 'ColorPicker',

  setup(props, context) {
    // 引用类型的数据，用于获取 canvas 元素
    let canvas = ref(null);
    let indicatorPosition = 0
    // 画布的宽度和高度
    let canvasWidth = 190;
    let canvasHeight = 100;
    // 颜色选择器的宽度和高度
    let colorSelectorWidth = 200;
    let colorSelectorHeight = 20;
    // 预设颜色数组
    let colorSelectorColors = [
      '#FF0000', '#FF2400', '#FF4800', '#FF6B00', '#FF8F00', '#FFB200', '#FFD600', '#FFFF00',
      '#D6FF00', '#B2FF00', '#8FFF00', '#6BFF00', '#48FF00', '#24FF00', '#00FF00', '#00FF24',
      '#00FF48', '#00FF6B', '#00FF8F', '#00FFB2', '#00FFD6', '#00FFFF', '#00D6FF', '#00B2FF',
      '#008FFF', '#006BFF', '#0048FF', '#0024FF', '#0000FF', '#2400FF', '#4800FF', '#6B00FF',
      '#8F00FF', '#B200FF', '#D600FF', '#FF00FF', '#FF00D6', '#FF00B2', '#FF008F', '#FF006B',
      '#FF0048', '#FF0024', '#FF0000'
    ];

    // 状态对象，用于存储选中的颜色和索引
    let state = reactive({
      selectedColor: colorSelectorColors[0],
      selectedColorIndex: 0
    });
    // 默认颜色
    let defaultColor = 'red';
    function handleClick(event) {
      // 获取画布位置信息
      let rect = canvas.value.getBoundingClientRect();
      // 计算点击位置的颜色索引
      let x = event.offsetX;
      let y = event.offsetY;
      // 获取画布上点击位置的像素数据
      let ctx = canvas.value.getContext('2d');
      let pixel = ctx.getImageData(x, y, 1, 1).data;
      // 将像素数据转换为颜色值
      let color = rgbToHex(pixel[0], pixel[1], pixel[2]);
      let rgb = `rgb(${pixel[0]}, ${pixel[1]}, ${pixel[2]})`
      // 更新选中的颜色
      state.selectedColor = color;

      // 更新指示点的位置
      this.indicatorPosition = calculateIndicatorPosition(color);
      // console.log(state.indicatorPosition, 'state.indicatorPosition', color);
      // console.log('color-main:', {hex:state.selectedColor, rgb})
      context.emit('change', { hex: state.selectedColor, rgb })
    }

    // 处理点击颜色选择器事件
    function selectColor(event) {
      // 获取颜色选择器位置信息
      let rect = event.target.getBoundingClientRect();
      let x = event.offsetX;
      let index = Math.floor(x / (rect.width / colorSelectorColors.length));
      if (index < 0) {
        index = 0// 防止索引小于0
      }
      // 更新选中的颜色和索引
      state.selectedColor = colorSelectorColors[index];
      state.selectedColorIndex = index;
      // console.log(event, index, state.selectedColor);
      this.indicatorPosition = x
      // console.log(x, event);
      updateMainColor(state.selectedColor);
    }
    // 处理点击预设颜色事件
    function selectPresetColor(color) {
      // 将预设颜色转换为十六进制格式
      let [h, s, l] = color.match(/\d+(\.\d+)?/g).map(Number);
      state.selectedColor = hslToHex(h, s, l);
      this.indicatorPosition = calculateIndicatorPosition(state.selectedColor);
      // console.log(color, 'ahsdkjashd');
      // 更新选中的颜色
      updateMainColor(state.selectedColor);
    }
    // HSL 转换为十六进制颜色格式
    function hslToHex(h, s, l) {
      // 转换 HSL 到 RGB
      h /= 360;
      s /= 100;
      l /= 100;

      let r, g, b;

      if (s === 0) {
        r = g = b = l; // HSL 的饱和度为0时，RGB 的每个分量都是L的值
      } else {
        let hueToRgb = (p, q, t) => {
          if (t < 0) t += 1;
          if (t > 1) t -= 1;
          if (t < 1 / 6) return p + (q - p) * 6 * t;
          if (t < 1 / 2) return q;
          if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
          return p;
        };

        let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        let p = 2 * l - q;

        r = hueToRgb(p, q, h + 1 / 3);
        g = hueToRgb(p, q, h);
        b = hueToRgb(p, q, h - 1 / 3);
      }

      // 转换 RGB 到十六进制
      let toHex = (c) => {
        let hex = Math.round(c * 255).toString(16);
        return hex.length === 1 ? '0' + hex : hex;
      };

      let hexColor = '#' + toHex(r) + toHex(g) + toHex(b);
      return hexColor.toUpperCase(); // 转换为大写形式
    }

    function rgbToHex(r, g, b) {
      return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    }
    // 初始化画布
    onMounted(() => {
      let ctx = canvas.value.getContext('2d');
      let gradient = ctx.createLinearGradient(0, 0, canvasWidth, canvasHeight);
      gradient.addColorStop(0, 'white');
      gradient.addColorStop(1, 'black');
      gradient.addColorStop(0.5, defaultColor);
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);
    });
    // 更新主画布颜色
    function updateMainColor(color) {
      let mainCanvas = canvas.value;
      let mainCtx = mainCanvas.getContext('2d');
      let gradient = mainCtx.createLinearGradient(0, 0, canvasWidth, canvasHeight);
      gradient.addColorStop(0, 'white');
      gradient.addColorStop(1, 'black');
      gradient.addColorStop(0.5, color);
      mainCtx.fillStyle = gradient;
      mainCtx.fillRect(0, 0, canvasWidth, canvasHeight);
      let rgb = hexToRgb(color)
      // console.log('color-main:', {hex: color, rgb:`rgb(${rgb.r},${rgb.g},${rgb.b})`})
      context.emit('change', {hex: color, rgb:`rgb(${rgb.r},${rgb.g},${rgb.b})`})
    }
    function calculateIndicatorPosition(selectedColor) {
      // console.log(selectedColor, 'selectedColor');
      let selectedRgb = hexToRgb(selectedColor);
      // console.log(selectedRgb, 'selectedRgb');
      let minDistance = Infinity;
      let closestIndex = 0;

      // 遍历颜色选择器中的所有颜色，计算与选定颜色的欧氏距离
      for (let i = 0; i < colorSelectorColors.length; i++) {
        let color = colorSelectorColors[i];
        let colorRgb = hexToRgb(color);
        let distance = Math.sqrt(
          Math.pow(selectedRgb.r - colorRgb.r, 2) +
          Math.pow(selectedRgb.g - colorRgb.g, 2) +
          Math.pow(selectedRgb.b - colorRgb.b, 2)
        );
        // console.log(distance, 'distance');
        // 更新最小距离和最近颜色的索引
        if (distance < minDistance) {
          minDistance = distance;
          closestIndex = i;
          // console.log(i, 'closestIndex');
        }
      }

      // 计算指示器位置并返回
      let positionRatio = closestIndex / (colorSelectorColors.length - 1);
      // console.log(positionRatio, 'positionRatio');
      let absolutePosition = positionRatio * colorSelectorWidth;
      return `${absolutePosition}`;
    }

    // 辅助函数：将十六进制颜色转换为RGB对象
    function hexToRgb(hex) {
      // 从十六进制颜色字符串中提取RGB分量
      let bigint = parseInt(hex.slice(1), 16);
      let r = (bigint >> 16) & 255;
      let g = (bigint >> 8) & 255;
      let b = bigint & 255;
      return { r, g, b };
    }

    // 生成颜色预设
    let colorPresets = generateColorPresets();
    // console.log(colorPresets, 'colorPresets');
    function generateColorPresets() {
      let presets = [];
      let hues = [0, 30, 60, 120, 180, 240, 270, 300, 330];
      // let hues = [0, 30, 60, 120, 180, 240, 270, 300, 330];
      let baseLightness = 50;
      let lightnessStep = (90 - baseLightness) / 4; // 将亮度值分为4个部分

      for (let i = 0; i < 5; i++) {
        // 列数改为4
        let presetColumn = [];
        hues.forEach((hue, index) => {
          let lightness;
          if (i === 3 && index === 2) {
            lightness = presets[2][index].split(",")[2].split(")")[0]; // 使用第三列的亮度值
          } else {
            lightness = baseLightness + i * lightnessStep; // 其他列正常计算亮度值
          }
          let colorValue = `hsl(${hue}, 100%, ${lightness}%)`;
          presetColumn.push(colorValue);
        });
        presets.push(presetColumn);
      }
      // console.log(presets[0][0]);
      return presets;
    }
    //   预设颜色数组
    let presetColors = [
      '#000000', '#FFFFFF', '#FF0000', '#FFA500', '#FFFF00', '#008000', '#00FFFF', '#0000FF', '#800080'
    ];

    return {
      canvas,
      canvasWidth,
      canvasHeight,
      colorSelectorWidth,
      colorSelectorHeight,
      colorSelectorColors,
      state,
      handleClick,
      selectColor,
      selectPresetColor,
      colorPresets,
      indicatorPosition,
      presetColors  // 记住所做的修改
    };
  }
};
</script>

<style scoped lang="scss">
.color-picker-title,
.result {
  width: 100%;
  text-align: left;
}

.color-preset {
  background-color: hsl(60, 100%, 80%);
}


.color-picker-box {
  position: absolute;
  left: 3px;
  top: 3px;
  bottom: 3px;
  max-width: 300px;
  padding: 4px;
  
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  background: #fff;
  border-radius: 3px;
  box-sizing: border-box;
}

.color-picker {
  display: inline-block;
}

.show-color-box {
  display: flex;
  width: 100%;
  align-items: center;
  box-sizing: border-box;
  padding: 0px 8px;
  background: #f1f1f1;
  border-radius: 4px;
}

.color-selector-wrap {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .color-selector-name {
    font-size: 12px;
  }
}

.color-selector {
  width: 130px;
  height: 10px;
  position: relative;
  cursor: pointer;
  border-radius: 5px;
  background: linear-gradient(to right, #FF0000, #FF2400, #FF4800, #FF6B00, #FF8F00, #FFB200, #FFD600, #FFFF00, #D6FF00, #B2FF00, #8FFF00, #6BFF00, #48FF00, #24FF00, #00FF00, #00FF24, #00FF48, #00FF6B, #00FF8F, #00FFB2, #00FFD6, #00FFFF, #00D6FF, #00B2FF, #008FFF, #006BFF, #0048FF, #0024FF, #0000FF, #2400FF, #4800FF, #6B00FF, #8F00FF, #B200FF, #D600FF, #FF00FF, #FF00D6, #FF00B2, #FF008F, #FF006B, #FF0048, #FF0024, #FF0000);
}

.color-presets {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.showColor {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.color-preset-row {
  display: flex;
  gap: 4px;
}

.color-preset {
  width: 17px;
  height: 17px;
  cursor: pointer;
  border-radius: 3px;
}

.color-selector-indicator {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background-color: black;
  position: absolute;
  border: 2px solid white;
  transform: translateX(-65%);
}
</style>
